<template>
  <div>
    <h3>用户列表</h3>
    <ul>
        <li v-for="user in userList" :key="user.id">
            {{ user.name }} : {{ user.password }}
            <button @click="deleteUser(user.id)">删除</button>
            <button @click="updateUser(user)">修改</button>
        </li>
    </ul>
  </div>

</template>

<script>
    import axios from 'axios';
    export default {
        name:'UserList',
        data(){
            return {
                userList:[]
            }
        },
        methods:{
            initUserList(){
                axios.get('http://localhost:8081/api1/getAll').then(
                resopnse => {this.userList=resopnse.data},
                error => {alert(error.message)})
            },
            deleteUser(id){
                axios.delete(`http://localhost:8081/api1/delete?id=${id}`).then(
                resopnse => {
                    alert(resopnse.data)
                    // 删除成功后，从 userList 中移除相应的用户
                    this.userList = this.userList.filter((user) => user.id !== id);
                },
                error => {alert(error.message)}
            )},
            updateUser(user){
                axios.put('http://localhost:8081/api1/update',user).then(
                resopnse => {
                    alert(resopnse.data)
                    
                },
                error => {alert(error.message)}
            )}
        },
        mounted(){
            axios.get('http://localhost:8081/api1/getAll').then(
                resopnse => {this.userList=resopnse.data},
                error => {alert(error.message)}
            ),
            this.$bus.$on('updateList',this.initUserList)
        }
    }
</script>

<style>

</style>